package com.hzqy.service.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.utils.ActivityUtils;
import com.hzqy.commons.utils.MD5;
import com.hzqy.commons.utils.PublicUtil;
import com.hzqy.persistence.dao.activity.ActivityAnswerDao;
import com.hzqy.persistence.dao.activity.ActivityModelDao;
import com.hzqy.persistence.dao.activity.ActivityDrawDao;
import com.hzqy.persistence.dao.activity.ActivityIdouDao;
import com.hzqy.persistence.dao.commons.CommonsDao;
import com.hzqy.service.activity.interf.ActivityUserFactory;
import com.hzqy.service.activity.interf.GetFromIouIface;
import com.hzqy.service.activity.load.ActivityAnswerUser;
import com.hzqy.service.activity.load.ActivityAwardUser;
import com.hzqy.service.activity.load.DayActivityCount;
import com.hzqy.service.activity.load.WeekActivityCount;
import com.hzqy.service.core.GenericServiceBean;
import com.hzqy.web.vo.PmsOrgVo;
import com.hzqy.web.vo.PmsUserVo;
import com.hzqy.web.vo.StatDataUserSextupleVo;
import com.hzqy.web.vo.SysProductVo;
import com.hzqy.web.vo.UserBillVo;
import com.hzqy.web.vo.activity.AcContentActionVo;
import com.hzqy.web.vo.activity.AcIdouVo;
import com.hzqy.web.vo.activity.ActivityAwardVo;
import com.hzqy.web.vo.activity.ActivityViewButtonVo;
import com.hzqy.web.vo.activity.ActivityViewVo;
import com.hzqy.web.vo.activity.AnswerContentVo;
import com.hzqy.web.vo.activity.AnswerUserVo;
import com.hzqy.web.vo.activity.AwardUserVo;
import com.hzqy.web.vo.activity.LotteryRequestVo;
import com.hzqy.web.vo.activity.QuestionContentVo;
import com.hzqy.web.vo.activity.RequestVo;
import com.hzqy.web.vo.activity.ResponseVo;
import com.hzqy.web.vo.activity.ResultInfoVo;

@Service
public class ActivityModelServiceBean extends GenericServiceBean<PmsUserVo,ActivityModelDao, Integer>{
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	@Resource
	private ActivityModelDao activityModelDao;
	@Resource
	private ActivityAnswerDao activityAnswerDao;
	@Resource
	private ActivityDrawDao activityDrawDao;
	@Resource
	private ActivityIdouDao activityIdouDao;
	@Resource
	private CommonsDao commonsDao;
	
	@Override
	public ActivityModelDao getEntityDao() {
		return activityModelDao;
	}
	public AcContentActionVo selectActivity(String activityid) {
		AcContentActionVo acContentActionVo =activityModelDao.selectActivity(activityid);
		String startdate = "0000-00-00 00:00:00";
		String enddate = "2099-12-31 23:59:59";
		if(acContentActionVo!=null){
			startdate = acContentActionVo.getF_aca_startdate();
			enddate = acContentActionVo.getF_aca_enddate();
			Date startDate = PublicUtil.getDateFormat(startdate,"yyyy-MM-dd HH:mm:ss");
			Date endDate = PublicUtil.getDateFormat(enddate,"yyyy-MM-dd HH:mm:ss");
			Date nowdate = new Date();
			if(nowdate.getTime()>=startDate.getTime() && nowdate.getTime()<=endDate.getTime()){
				acContentActionVo.setFlagOnLine(true);
			}
		}else{//不存在该活动
			acContentActionVo = new AcContentActionVo();
			acContentActionVo.setFlagOnLine(false);
		}
		return acContentActionVo;
	}
	public List<ActivityViewVo> selectActivityView(Map<String, Object> map) {
		List<ActivityViewVo> viewlist = activityModelDao.selectActivityView(map);
		LOG.debug("selectActivityView-viewlist.size:"+viewlist.size()+"--f_av_activityid:"+map.get("f_av_activityid"));
		if(viewlist != null && viewlist.size() > 0){
			for(ActivityViewVo vo : viewlist){
				List<ActivityViewButtonVo> buttonlist = activityModelDao.selectActivityViewButtons(vo.getF_av_id());
				vo.setButtonlist(buttonlist);
			}
		}
		return viewlist;
	}
	
	private ActivityUserFactory userFactory(Map<String, String> paraMap){
		ActivityUserFactory activityUserFactory=null;
		if("question".equals(paraMap.get("f_aca_model"))){
			activityUserFactory=new ActivityAnswerUser(activityAnswerDao);
		}else{
			activityUserFactory=new ActivityAwardUser(activityDrawDao);
		}
		if("day".equals(paraMap.get("f_aca_time"))){
			activityUserFactory.setActivityCount(new DayActivityCount());
		}else if("week".equals( paraMap.get("f_aca_time") )){
			activityUserFactory.setActivityCount(new WeekActivityCount());
		}
		return activityUserFactory;
	}
	/**
	 * 获取用户参加活动次数
	 * @param paraMap
	 * @return
	 * paraMap.put("serverid", serverid);
		paraMap.put("activityid", activityid);
		paraMap.put("f_aca_time", f_aca_time);
		paraMap.put("f_aca_model", f_aca_model);
	 */
	public int getActivityUserCount(Map<String, String> paraMap) {
		LOG.debug("getActivityUserCount--f_aca_model:"+paraMap.get("f_aca_model"));
		ActivityUserFactory activityUserFactory=userFactory(paraMap);
		return activityUserFactory.getActivityUserCount(paraMap);
	}
	
	public int getAwardActivityUserCount(Map<String, String> paraMap) {
		ActivityUserFactory activityUserFactory=userFactory(paraMap);
		return activityUserFactory.getAwardActivityUserCount(paraMap);
	}
	public ResultInfoVo getLotteryResultNew(LotteryRequestVo requestVo) {
		String url = null;
		if (requestVo != null) {
			url = requestVo.getUrl();
			if (!url.endsWith("?")) {
				url = url + "?";
			}
			String code = MD5.encrypt32(requestVo.getActivityid()+requestVo.getUserid());
			
			url += "activityId=" + requestVo.getActivityid();
			url += "&account=" + requestVo.getUserid();
			url += "&code=" + code;
		}
		LOG.debug("抽奖url地址:"+url);
		ResultInfoVo res = ActivityUtils.sendPost(url,"GBK");
		//this.insertDrawData(res,phone,code,ids,prizes);
		return res;
	}
	
	public ResultInfoVo getLotteryResult(LotteryRequestVo requestVo) {
		String url = null;
		if (requestVo != null) {
			url = requestVo.getUrl();
			if (!url.endsWith("?")) {
				url = url + "?";
			}
			url += "action=" + requestVo.getAction();
			url += "&userid=" + requestVo.getUserid();
			url += "&activityid=" + requestVo.getActivityid();
			url += "&awardlevel=" + requestVo.getAwardlevel();
			url += "&vt=" + requestVo.getVt();
			url += "&ts=" + requestVo.getTs();
			url += "&digest=" + requestVo.getDigest();
			url += "&phone=" + requestVo.getPhone();
		}
		LOG.debug("url地址:"+url);
		ResultInfoVo res = ActivityUtils.sendPostold(url,"GBK");
		//this.insertDrawData(res,phone,code,ids,prizes);
		return res;
	}
	
	public List<ActivityAwardVo> selectActivityAward(Map<String, String> map) {
		List<ActivityAwardVo> list=activityModelDao.selectActivityAward(map);
		return list;
	}
	public int insertUserLotteryResult(Map<String, String> map) {
		ActivityUserFactory activityUserFactory=userFactory(map);
		int lid=activityUserFactory.insertActivityUserData(map);
		return lid;
	}
	public List getAwardActivityUserList(Map<String, String> paraMap) {
		ActivityUserFactory activityUserFactory=userFactory(paraMap);
		List list=activityUserFactory.activityUserList(paraMap);
		return list;
	}
	/**
	 * 查询题目信息
	 * @param activityid
	 * @param numberId
	 * @return
	 */
	public QuestionContentVo selectQuestionTitle(String activityid,String numberId) {
		QuestionContentVo questionContentVo = new QuestionContentVo();
		questionContentVo.setF_csqc_viewindex(Integer.parseInt(numberId));
		questionContentVo.setF_csqc_activityid(activityid);
		questionContentVo=activityAnswerDao.selectQuestionTitle(questionContentVo);
		if(questionContentVo != null){
			List<AnswerContentVo> answerList = activityAnswerDao.selectQuestionAnswer(questionContentVo.getF_csqc_id());
			questionContentVo.setAnswerList(answerList);
			return questionContentVo;
		}else{
			return null;
		}
	}
	public int selectQuestionCount(String activityid) {
		int counts=activityAnswerDao.selectQuestionCount(activityid);
		return counts;
	}
	public int updateActivityUserData(Map<String, String> map) {
		ActivityUserFactory activityUserFactory=userFactory(map);
		int flag=activityUserFactory.updateActivityUserData(map);
		return flag;
	}
	
	//
	public int sendIdouMethod(Map<String, String> map) {
		AcContentActionVo acActionVo=this.selectActivity(map.get("activityid"));
		String source = "";//活动编号
		String f_sp_id = "0";//活动产品
		String plid = "";//分配ID计划
		String siteid = "";//增值网元编号
		String serverid=map.get("serverid");
		String phone=map.get("phone");
		if(acActionVo != null){
			source = acActionVo.getF_aca_code();
			f_sp_id = acActionVo.getF_aca_productid();
			plid = acActionVo.getF_aca_idouid()+"";
			siteid = acActionVo.getF_aca_siteid();
		}
		int flag=Integer.parseInt(map.get("flag")); 
		boolean act_date = acActionVo.isFlagOnLine();
		if(act_date == true){
			int f_ai_id = 0;
			//判断是否送过idou
			int bo = 0;
			if(flag == 1){//只匹配产品ID
				bo = this.decideSendIdou("",f_sp_id,serverid);
			}else if(flag==2){
				bo = 0; //2是可以重复送idou,不进行判断
			}else{
				bo = this.decideSendIdou(map.get("activityid"),f_sp_id,serverid);
			}
			//未送i豆
			if(bo == 0){
				//送idou
				int idou_sum = Integer.valueOf(map.get("f_aoa_idou"));
				
				RequestVo reqVo = new RequestVo();
				reqVo.setPlid(Integer.valueOf(plid));
				reqVo.setSiteid(siteid);
				reqVo.setCount(idou_sum);
				reqVo.setUserid(serverid);
				ResponseVo respVo = this.sendIdou(reqVo,map);
				//获取结果插入idou记录
				AcIdouVo acIdouVo = new AcIdouVo();
				acIdouVo.setF_ai_count(idou_sum);
				acIdouVo.setF_ai_activityid(map.get("activityid"));
				acIdouVo.setF_ai_productid(f_sp_id);
				acIdouVo.setF_ai_phone(phone);
				f_ai_id = this.insertIdouRecord(respVo,acIdouVo,null,serverid);
			}
			return f_ai_id;
		}else{
			return 0;
		}
		
	}

	/**
	 * 判断是否已送i豆
	 * @return 大于0:已送，0：未送
	 */
	public int decideSendIdou(String actcode,String productid,String serverid){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("actcode", actcode);
		map.put("serverid", serverid);
		map.put("productid", productid);
		List<AcIdouVo> acIdouList = activityIdouDao.selectIdouList(map);
		if(acIdouList.size()>0){LOG.debug(serverid+"已送I豆");return acIdouList.get(0).getF_ai_id();}
		else{LOG.debug(serverid+"未送I豆");return 0;}
	}

	/**
	 * 送Idou
	 * @param reqVo
	 * @return
	 */
	public ResponseVo sendIdou(RequestVo reqVo,Map map){
		ResponseVo respVo = GetFromIouIface.getXmlStringRetIdou(reqVo,map);
		if(reqVo!=null){
			LOG.debug("i豆计划："+reqVo.getPlid()+",i豆网元编号："+reqVo.getSiteid()+",用户："+reqVo.getUserid());
		}
		return respVo;
	}
	
	/**
	 * 插入idou记录
	 * @param respVo
	 */
	public int insertIdouRecord(ResponseVo respVo,AcIdouVo acIdouVo,String sign,String serverid){
		if(respVo != null){
			LOG.debug("送idou返回码："+respVo.getRetCode());
			if("0000".equals(respVo.getRetCode())){
				acIdouVo.setF_ai_status(0);
			}else{
				acIdouVo.setF_ai_status(1);
			}
			acIdouVo.setF_ai_retu(respVo.getRetCode());
		}else{
			acIdouVo.setF_ai_status(1);
			acIdouVo.setF_ai_retu("插入失败");
		}
		int result = 0;
		if(sign == null || "normal".equals(sign)){//正常插入I豆
			acIdouVo.setF_ai_serverid(serverid);
			result = activityIdouDao.insertIdouRecord(acIdouVo);
		}else if("repair".equals(sign)){//补送I豆
			result = activityIdouDao.insertIdouRecordRepair(acIdouVo);
		}
		if(result == 0){
			LOG.debug(serverid+"插入idou记录失败");
		}else{
			LOG.debug(serverid+"插入idou记录成功");
		}
		return result;
	}
	
	public String getDrawPhone(Map map){
		String phone=activityDrawDao.getDrawPhone(map);
		return phone;
	}
	

	public Map<String, Object> selectOnlineActivityProductInfo(String resolution) {
		List<AcContentActionVo> list=activityModelDao.selectOnlineActivity();//查询当前在线的所有活动
		AcContentActionVo acContentActionVo = null;
		if(list != null && list.size() > 0 && "1".equals( resolution) ){
			for(AcContentActionVo vo : list){
				if(vo.getF_aca_alert() == 2){
					acContentActionVo = vo;
					break;
				}
			}
		}else if(list != null && list.size() > 0 && "2".equals(resolution)) {
			for(AcContentActionVo vo : list){
				if(vo.getF_aca_hdalert()==2){
					acContentActionVo = vo;
					break;
				}
			}
		}
		if(acContentActionVo==null){
			return null;
		}
		acContentActionVo = activityModelDao.selectContentAction(acContentActionVo.getF_aca_id()+"");
		LOG.debug("acContentActionVo.getActivity_url():"+acContentActionVo.getActivity_url());
		String productid=acContentActionVo.getF_aca_productid();
		LOG.debug("分辨率resolution:"+resolution+"--在线活动对应的产品ID:"+productid+"--活动ID:"+acContentActionVo.getF_aca_id());
		List<SysProductVo>proList=commonsDao.selectProductListByProductId(Integer.parseInt(productid));
		List<PmsOrgVo> orgList = commonsDao.selectOrgCodeByProductId(Integer.parseInt(productid));
		String SPID="120000";
		if(orgList.size()>0){
			SPID=orgList.get(0).getF_po_code();
		}
		Map<String, Object>map=new HashMap<String, Object>();
		map.put("proList", proList);
		map.put("acContentActionVo", acContentActionVo);
		map.put("SPID", SPID);
		return map;
	}
	
	
	public int insertActUserOrder(UserBillVo userBillVo){
		int flag = activityModelDao.insertUserBill(userBillVo);
		return flag;
				
	}
	public List<AwardUserVo> selectUseraward(AwardUserVo awardUserVo) {
		if("1".equals(awardUserVo.getF_au_cdate())){//
			awardUserVo.setF_au_cdate(PublicUtil.getCurDateTime("yyyy-MM-dd"));
		}
		return activityDrawDao.selectUseraward(awardUserVo);
	}
	
	public List<QuestionContentVo> selectQuestions(QuestionContentVo questionContentVo){
		return activityAnswerDao.selectQuestions(questionContentVo);
	}
	
	public int selectCountByOrg(AnswerUserVo answerUserVo) {
		return activityDrawDao.selectCountByOrg(answerUserVo);
	}
	
	public int selectCountByServerId(AnswerUserVo answerUserVo) {
		return activityDrawDao.selectCountByServerId(answerUserVo);
	}
	
	public List<QuestionContentVo> selectAllQuestionAnswerByActivityid(String activityid) {
		Map<String, Object>map=new HashMap<String, Object>();
		map.put("f_csqc_activityid", activityid);
		List<QuestionContentVo> questionContentVoList = activityAnswerDao.selectQuestionList(map);
		for(int i=0;i<questionContentVoList.size();i++){
			List<AnswerContentVo> answerList = activityAnswerDao.selectQuestionAnswer(questionContentVoList.get(i).getF_csqc_id());
			questionContentVoList.get(i).setAnswerList(answerList);
		}
		return questionContentVoList;
	}
	
	public int insertAnswerUser(String jsonStr) {
		JSONObject json = JSONObject.parseObject(jsonStr);
		String f_aqu_serverid = json.getString("f_aqu_serverid");
		int f_aqu_activityid = Integer.parseInt(json.getString("f_aqu_activityid"));
		JSONArray jsonArray = json.getJSONArray("answer");
		int flag = 0;
		for(int i=0;i<jsonArray.size();i++){
			AnswerUserVo answerUserVo = new AnswerUserVo();
			answerUserVo.setF_aqu_serverid(f_aqu_serverid);
			answerUserVo.setF_aqu_activityid(f_aqu_activityid);
			JSONObject jsonQuestionAnswer = JSONObject.parseObject(jsonArray.get(i).toString());
			answerUserVo.setF_aqu_obligate1(jsonQuestionAnswer.getString("f_aqu_obligate1"));
			answerUserVo.setF_aqu_obligate2(jsonQuestionAnswer.getString("f_aqu_obligate2"));
			flag = activityAnswerDao.insertAnswerUser(answerUserVo);
		}
		return flag;
	}
	
	public int insertOrUpdateIdou(AcIdouVo acIdouVo) throws ParseException {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("f_ai_serverid", acIdouVo.getF_ai_serverid());
		map.put("f_ai_activityid", acIdouVo.getF_ai_activityid());
		AcIdouVo aiv = activityIdouDao.selectIdouByIdActId(map);//获取最新的数据
		int f_ai_count = 1;
		int flag = 0;
		LOG.debug(aiv+"");
		if(aiv != null) {
			Date endDate = new Date();//当前时间
			String startDate = aiv.getF_ai_date();//最新的一条数据时间
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date beginDate = format.parse(startDate);
			int differDay = (int)(endDate.getTime() - beginDate.getTime())/(24*60*60*1000);
			LOG.debug("differDay = "+differDay+";endDate="+endDate+";beginDate="+beginDate);
			if(differDay==1) {//当天未签到，加一
				f_ai_count = aiv.getF_ai_count() + 1;
			}
			map.put("f_ai_count", f_ai_count);
			if(differDay > 0){//当天未签到，执行更新操作
				flag = activityIdouDao.updateIdou(map);
			}else {//已签到不执行更新
				flag = 2;
			}
		}else {
			acIdouVo.setF_ai_productid("0");
			acIdouVo.setF_ai_count(1);
			acIdouVo.setF_ai_status(0);
			acIdouVo.setF_ai_retu("1");
			flag = activityIdouDao.insertIdouRecord(acIdouVo);
		}
		return flag;
	}
	
	public Map<String,Object> selectIdouByIdActId(AcIdouVo acIdouVo) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("f_ai_serverid", acIdouVo.getF_ai_serverid());
		map.put("f_ai_activityid", acIdouVo.getF_ai_activityid());
		if("time".equals(acIdouVo.getF_ai_date())) {
			Date date = new Date();
			SimpleDateFormat f= new SimpleDateFormat("yyyy-MM-dd");
			map.put("f_ai_date", f.format(date));
		}
		AcIdouVo aiv = activityIdouDao.selectIdouByIdActId(map);
		if(aiv != null) {
			map.put("result", 1);
			map.put("aiv", aiv);
		}else {//表示今天未签到
			map.put("result", 0);
		}
		return map;
	}
	
	public int insertIdouInfo(AcIdouVo acIdouVo){
		acIdouVo.setF_ai_productid("0");
		acIdouVo.setF_ai_count(1);
		acIdouVo.setF_ai_status(0);
		acIdouVo.setF_ai_retu("1");
		return  activityIdouDao.insertIdouRecord(acIdouVo);
	}
	
	/**
	 *教育签到活动：
	 *   获取连续签到天数,从当天时间开始,向下查询，直到断档  
	 */
	public Map<String,Object> selectSignInCount(AcIdouVo acIdouVo) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("f_ai_serverid", acIdouVo.getF_ai_serverid());
		map.put("f_ai_activityid", acIdouVo.getF_ai_activityid());
		Calendar ca = Calendar.getInstance();
		ca.setTime(new Date());
		Date date = ca.getTime();
		SimpleDateFormat f= new SimpleDateFormat("yyyy-MM-dd");
		map.put("f_ai_date", f.format(date));
		AcIdouVo aiv = activityIdouDao.selectIdouByIdActId(map);
		int count = 0;
		while(aiv != null) {
			count ++;
			ca.add(Calendar.DATE, -1);
			date = ca.getTime();
			map.put("f_ai_date", f.format(date));
			aiv = activityIdouDao.selectIdouByIdActId(map);
		}
		map.put("count", count);
		return map;
	}
	
	/**
	 *教育签到活动：
	 *   获取签到天数,非连续
	 */
	public Map<String,Object> selectSignInCountOne(AcIdouVo acIdouVo) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("f_ai_serverid", acIdouVo.getF_ai_serverid());
		map.put("f_ai_activityid", acIdouVo.getF_ai_activityid());
		int count = activityIdouDao.selectIdouCount(map);
		map.put("count", count);
		return map;
	}
	
	public List<QuestionContentVo> selectQuestionAnswerList(QuestionContentVo questionContentVo) {
		Map<String, Object>map=new HashMap<String, Object>();
		map.put("f_csqc_activityid", questionContentVo.getF_csqc_activityid());
		map.put("f_csqc_contentid", questionContentVo.getF_csqc_contentid());
		map.put("f_csqc_viewindex", questionContentVo.getF_csqc_viewindex());
		List<QuestionContentVo> questionContentVoList = activityAnswerDao.selectQuestionListOne(map);
		for(int i=0;i<questionContentVoList.size();i++){
			List<AnswerContentVo> answerList = activityAnswerDao.selectQuestionAnswer(questionContentVoList.get(i).getF_csqc_id());
			questionContentVoList.get(i).setAnswerList(answerList);
		}
		return questionContentVoList;
	}
	public StatDataUserSextupleVo selectSextuplEuserData(StatDataUserSextupleVo sextupleVo) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("f_sdus_serverid", sextupleVo.getF_sdus_serverid());
		StatDataUserSextupleVo vo = activityIdouDao.selectSextuplEuserData(map);
		return vo;
	}
}
